<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 前台优惠券ajax类
 * @package  ajax
 * @subpackage  shop
 * @author   allen.qiang
 */

quanli_require('module/base/promotion/quanliCoupon.class.php');

class ajax_coupon {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && quanli_is_int($_REQUEST['operFlg'])) {

            switch($_REQUEST['operFlg']) {

                case 1: //查询优惠券
                    $this->searchCoupon();
                    break;

                case 2: //激活优惠券
                    $this->activateCoupon();
                    break;

                default:
                    returnJsonData('参数错误');
                    break;


            }

        } else {
            returnJsonData('参数错误');
        }

    }

    /**
     * 查询优惠券
     */
    private function searchCoupon() {

        global $G_SHOP;

        //检查是否登录
        if (!$G_SHOP->currentPCustID) {
            returnJsonData('请先登录', 404);
        }

        if (!isset($_REQUEST['page']) || !quanli_is_int($_REQUEST['page'])) {
            $_REQUEST['page'] = 1;
        }

        //实例优惠券类
        $ebsigCoupon = new quanliCoupon();

        //查询订单信息
        $args_array = array(
            'pcustID' => $G_SHOP->currentPCustID,
            'page' => $_REQUEST['page'],
            'used' => $_REQUEST['used'],
            'rp' => 5,
            'sortname' => 'createTime',
            'sortorder' => 'DESC'
        );

        $result_array['coupon'] = $ebsigCoupon->searchCouponCode( $args_array );
        if ($result_array['coupon']) {

            $result_array['paging'] = shop_page($args_array['page'], $args_array['count'], $args_array['rp'], 'javascript: G.coupon.search(%d);', $G_SHOP->smarty);

            returnJsonData('ok', 200, $result_array);

        } else {
            returnJsonData('优惠券信息没有找到', 404);
        }

    }

    /**
     * 激活优惠券
     */
    private function activateCoupon() {

        global $G_SHOP;

        //检查是否登录
        if (!$G_SHOP->currentPCustID) {
            returnJsonData('请先登录', 404);
        }

        if (!isset($_REQUEST['coupon_code']) || empty($_REQUEST['coupon_code']) || strlen($_REQUEST['coupon_code']) > 18) {
            returnJsonData('请输入输入优惠券');
        }

        //实例优惠券类
        $ebsigCoupon = new quanliCoupon();

        $result_array = $ebsigCoupon->activateCoupon( $G_SHOP->currentPCustID, $_REQUEST['coupon_code'] );

        returnJsonData($result_array['message'], $result_array['code']);

    }

}